﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Extensil.Common;
using Extensil.Common.CategoryHandler;
using Extensil.Common.CategoryHandler.Discovery;
using Extensil.Common.Progress;
using Extensil.Processor;

namespace Extensil.Category.Discovery
{
    public partial class DiscoverySetting :BaseSetting
    {
        public static BackgroundWorker bw = new BackgroundWorker();
        public DiscoverySetting()
        {
            InitializeComponent();
            cbEnableDP.Checked = CategorySection.GetConfig().DiscoverySection.IsActive;
            LoadProbes();
            PopulateProbeInterval();
            cbAutoUpgrade.Checked = CategorySection.GetConfig().DiscoverySection.IsAutoUpdateEnabled;
        }
        void PopulateProbeInterval()
        {
            List<ComboPropertyParam> probeInts = new List<ComboPropertyParam>();
            probeInts.Add(new ComboPropertyParam("10 mins", (10 * 60 * 1000).ToString()));
            probeInts.Add(new ComboPropertyParam("1 hr", (60 * 60 * 1000).ToString()));
            probeInts.Add(new ComboPropertyParam("4 hr", (4 * 60 * 60 * 1000).ToString()));
            cbProbeInterval.DisplayMember = "Key";
            cbProbeInterval.ValueMember = "Value";
            cbProbeInterval.DataSource = probeInts;

            cbProbeInterval.SelectedIndexChanged+=new EventHandler(cbProbeInterval_SelectedIndexChanged);
            cbProbeInterval.SelectedValue = CategorySection.GetConfig().DiscoverySection.ProbeInterval.ToString();
        }
        private void cbEnableDP_CheckedChanged(object sender, EventArgs e)
        {
            using(ConfigModifier cm = new ConfigModifier())
            {
                cm.AllowDiscovery = cbEnableDP.Checked;
            }
            // panel1.Enabled = cbEnableDP.Checked;
        }
        void LoadProbes()
        {
            List<ProbeItem> prbList = new List<ProbeItem>();
            foreach(Probe prb in CategorySection.GetConfig().DiscoverySection)
            {
                prbList.Add(new ProbeItem(prb.Name, prb.Handler, prb.IsActive));
            }
            dgvProbingList.DataSource = prbList;
        }

        private void dgvProbingList_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            dgvProbingList.Columns["IsActive"].Visible = false;
            dgvProbingList.Columns["Edit"].DisplayIndex = dgvProbingList.Columns.Count - 3;
            dgvProbingList.Columns["Delete"].DisplayIndex = dgvProbingList.Columns.Count - 2;
            dgvProbingList.Columns["Enable"].DisplayIndex = dgvProbingList.Columns.Count - 1;
            if(dgvProbingList.Rows.Count > 0)
                dgvProbingList.Rows[0].Selected = false;
            foreach(DataGridViewRow dr in dgvProbingList.Rows)
            {
                ((DataGridViewImageCell)dr.Cells["Enable"]).Value = (bool)dr.Cells["IsActive"].Value 
                    ? Extensil.Properties.Resources.enable 
                    : Extensil.Properties.Resources.disable;
            }
        }

        private void dgvProbingList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if(e.ColumnIndex == dgvProbingList.Columns["Edit"].Index)
            {
                Probe prb = CategorySection.GetConfig().DiscoverySection[dgvProbingList["Name", e.RowIndex].Value.ToString()];
                ProbeConfiguration pc = new ProbeConfiguration(prb);
                if(pc.ShowDialog() == DialogResult.OK)
                {
                    using(ConfigModifier cm = new ConfigModifier())
                    {
                        cm.EditProbe(dgvProbingList["Name", e.RowIndex].Value.ToString(), pc.Probe);
                        dgvProbingList["Name", e.RowIndex].Value = pc.Probe.Name;
                        dgvProbingList["Handler", e.RowIndex].Value = pc.Probe.Handler;
                    }
                }
            }
            else if(e.ColumnIndex == dgvProbingList.Columns["Delete"].Index)
            {
                if(AlertBox.ShowDialog("Are you sure you want to delete the probe?", "Alert", AlertBoxButtons.YesNo) == AlertResult.Yes)
                {
                    using(ConfigModifier cm = new ConfigModifier())
                    {
                        cm.DeleteProbe(dgvProbingList["Name", e.RowIndex].Value.ToString());
                    }
                    LoadProbes();
                }
            }
            else if(e.ColumnIndex == dgvProbingList.Columns["Enable"].Index)
            {
                using(ConfigModifier cm = new ConfigModifier())
                {
                    ((DataGridViewImageCell)dgvProbingList["Enable", e.RowIndex]).Value = cm.ToggleProbe(dgvProbingList["Name", e.RowIndex].Value.ToString())
                    ? Extensil.Properties.Resources.enable
                    : Extensil.Properties.Resources.disable;
                }
                
            }
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            ProbeConfiguration pc = new ProbeConfiguration();
            if(pc.ShowDialog() == DialogResult.OK)
            {
                using(ConfigModifier cm = new ConfigModifier())
                {
                    cm.AddProbe(pc.Probe);
                }
                LoadProbes();
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Zipped Folder(*.zip)|";
            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtHandlerPlugin.Text = openFileDialog1.FileName;
                btnSubmit.Enabled = true;
            }
        }

        private void txtHandlerPlugin_TextChanged(object sender, EventArgs e)
        {
            btnSubmit.Enabled = true;
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            RunWorkerProcess();
        }
        void RunWorkerProcess()
        {
            bw = new BackgroundWorker();
            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(AddHandler);
            bw.ProgressChanged += new ProgressChangedEventHandler(InstallManager_Event);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync();
        }
        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnSubmit.Enabled = false;
        }
        void InstallManager_Event(object sender, ProgressChangedEventArgs e)
        {
            //ProgressStatus ts = (ProgressStatus)e.UserState;
            //pUpdate.Add(ts, e.ProgressPercentage);
        }
        void AddHandler(object sender, DoWorkEventArgs e)
        {
            try
            {
                PluginManager pm = new PluginManager(txtHandlerPlugin.Text, ReportStatus);
                InstallResult res = pm.Install();
                if(res.IsSuccessFull)
                    bw.ReportProgress(100, new ProgressStatus(StatusSource.Main, "New handler installed successfully.", -1));
                else
                {
                    string message = "Some of the plugins could not be installed properly.";
                    foreach(Exception exc in res)
                        message += "\r\n\t" + exc.Message;

                    AlertBox.ShowDialog(message);
                }
            }
            catch(Exception exc)
            {
                AlertBox.ShowDialog(exc);
            }
        }
        public void ReportStatus(int progress, string message)
        {
            bw.ReportProgress(progress,
                new ProgressStatus(StatusSource.Task,
                message, 100));
        }

        private void cbAutoUpgrade_CheckedChanged(object sender, EventArgs e)
        {
            using(ConfigModifier cm = new ConfigModifier())
            {
                cm.AllowAutoUpgrade = cbAutoUpgrade.Checked;
            }
        }

        private void cbProbeInterval_SelectedIndexChanged(object sender, EventArgs e)
        {
            using(ConfigModifier cm = new ConfigModifier())
            {
                cm.ProbeInterval = Int32.Parse(cbProbeInterval.SelectedValue.ToString());
            }
        }
    }
}
